package com.xuzhiguang.light.gateway.core.filter;

import com.xuzhiguang.light.gateway.core.context.GatewayContext;

import java.util.List;

/**
 * @author xuzhiguang
 */
public class DefaultGatewayFilterChain implements GatewayFilterChain {

    private volatile int index;

    private final List<GatewayFilter> filters;

    public DefaultGatewayFilterChain(List<GatewayFilter> filters) {
        this.filters = filters;
        this.index = 0;
    }

    @Override
    public void doFilter(GatewayContext context) {

        GatewayFilter filter;
        if (index < filters.size() && (filter = filters.get(index)).shouldRun(context)) {

            index ++;
            try {
                filter.doFilter(context, this);
            } catch (Throwable e) {
                e.printStackTrace();
                context.setThrowable(e);
                doFilter(context);
            }
        }
    }
}
